{% extends "base.html" %}

{% block title %}数据库配置 - 数据预处理系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12 mb-4">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <h4 class="card-title mb-0">
                    <i class="fas fa-server me-2"></i>数据库配置管理
                </h4>
                <button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#addConfigModal">
                    <i class="fas fa-plus me-1"></i>添加配置
                </button>
            </div>
            <div class="card-body">
                {% if configs %}
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>配置名称</th>
                                <th>数据库类型</th>
                                <th>主机地址</th>
                                <th>端口</th>
                                <th>数据库名</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="configList">
                            {% for name, config in configs.items() %}
                            <tr>
                                <td><strong>{{ name }}</strong></td>
                                <td><span class="badge bg-info">{{ config.db_type.value }}</span></td>
                                <td>{{ config.host }}</td>
                                <td>{{ config.port }}</td>
                                <td>{{ config.database }}</td>
                                <td>
                                    <span class="badge bg-secondary" id="status-{{ name }}">未测试</span>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary me-1" onclick="testConnection('{{ name }}')">
                                        <i class="fas fa-link"></i> 测试
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" onclick="removeConfig('{{ name }}')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                {% else %}
                <div class="empty-state text-center py-5">
                    <i class="fas fa-database fa-3x text-muted mb-3"></i>
                    <h5>暂无数据库配置</h5>
                    <p class="text-muted">点击上方"添加配置"按钮开始配置数据库连接</p>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- 添加配置模态框 -->
<div class="modal fade" id="addConfigModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-plus me-2"></i>添加数据库配置
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addConfigForm">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="configName" class="form-label">配置名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="configName" name="name" required
                                   placeholder="例如: 生产数据库">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="dbType" class="form-label">数据库类型 <span class="text-danger">*</span></label>
                            <select class="form-select" id="dbType" name="db_type" required>
                                <option value="">请选择数据库类型</option>
                                <option value="mysql">MySQL</option>
                                <option value="postgresql">PostgreSQL</option>
                                <option value="sqlserver">SQL Server</option>
                                <option value="oracle">Oracle</option>
                                <option value="sqlite">SQLite</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-8 mb-3">
                            <label for="host" class="form-label">主机地址 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="host" name="host" required
                                   placeholder="localhost 或 IP地址">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label for="port" class="form-label">端口 <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="port" name="port" required
                                   placeholder="3306" min="1" max="65535">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label for="database" class="form-label">数据库名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="database" name="database" required
                                   placeholder="数据库名称">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="username" class="form-label">用户名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="username" name="username" required
                                   placeholder="数据库用户名">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="password" class="form-label">密码 <span class="text-danger">*</span></label>
                            <input type="password" class="form-control" id="password" name="password" required
                                   placeholder="数据库密码">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="charset" class="form-label">字符集</label>
                            <input type="text" class="form-control" id="charset" name="charset" 
                                   placeholder="utf8mb4" value="utf8mb4">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="connectionTimeout" class="form-label">连接超时(秒)</label>
                            <input type="number" class="form-control" id="connectionTimeout" name="connection_timeout" 
                                   placeholder="30" value="30" min="1" max="300">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-1"></i>保存配置
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let statusRefreshInterval;

$(document).ready(function() {
    // 启动状态刷新
    startStatusRefresh();
    
    // 页面卸载时清理定时器
    $(window).on('beforeunload', function() {
        if (statusRefreshInterval) {
            clearInterval(statusRefreshInterval);
        }
    });
    // 数据库类型变化时自动设置默认端口
    $('#dbType').change(function() {
        const dbType = $(this).val();
        const portMap = {
            'mysql': 3306,
            'postgresql': 5432,
            'sqlserver': 1433,
            'oracle': 1521,
            'sqlite': ''
        };
        
        if (portMap[dbType] !== undefined) {
            $('#port').val(portMap[dbType]);
        }
        
        // SQLite不需要主机和端口
        if (dbType === 'sqlite') {
            $('#host, #port, #username, #password').prop('disabled', true);
            $('#database').attr('placeholder', 'SQLite文件路径');
        } else {
            $('#host, #port, #username, #password').prop('disabled', false);
            $('#database').attr('placeholder', '数据库名称');
        }
    });
    
    // 表单提交
    $('#addConfigForm').submit(function(e) {
        e.preventDefault();
        addConfig();
    });
});

function addConfig() {
    const formData = {
        name: $('#configName').val(),
        db_type: $('#dbType').val(),
        host: $('#host').val(),
        port: $('#port').val(),
        database: $('#database').val(),
        username: $('#username').val(),
        password: $('#password').val(),
        charset: $('#charset').val(),
        connection_timeout: $('#connectionTimeout').val()
    };
    
    $.ajax({
        url: '/api/database/configs',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(formData)
    })
    .done(function(data) {
        if (data.success) {
            Notification.success('数据库配置添加成功');
            $('#addConfigModal').modal('hide');
            location.reload();
        } else {
            Notification.error('添加失败: ' + data.message);
        }
    })
    .fail(function() {
        Notification.error('添加配置失败');
    });
}

function testConnection(configName) {
    const btn = $(`button[onclick="testConnection('${configName}')"]`);
    const statusBadge = $(`#status-${configName}`);
    
    btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 测试中...');
    statusBadge.removeClass().addClass('badge bg-warning').text('测试中...');
    
    $.post(`/api/database/test/${configName}`)
        .done(function(data) {
            if (data.success) {
                statusBadge.removeClass().addClass('badge bg-success').text('连接正常');
                Notification.success('数据库连接测试成功');
            } else {
                statusBadge.removeClass().addClass('badge bg-danger').text('连接失败');
                Notification.error('连接测试失败: ' + data.message);
            }
        })
        .fail(function() {
            statusBadge.removeClass().addClass('badge bg-danger').text('连接失败');
            Notification.error('连接测试失败');
        })
        .always(function() {
            btn.prop('disabled', false).html('<i class="fas fa-link"></i> 测试');
        });
}

function removeConfig(configName) {
    if (confirm(`确定要删除配置"${configName}"吗？`)) {
        // TODO: 实现删除功能
        Notification.info('删除功能开发中...');
    }
}

function startStatusRefresh() {
    // 立即刷新一次
    refreshConnectionStatus();
    
    // 每30秒自动刷新状态
    statusRefreshInterval = setInterval(function() {
        refreshConnectionStatus();
    }, 30000);
}

function refreshConnectionStatus() {
    $.get('/api/database/status')
        .done(function(data) {
            if (data.success) {
                updateConnectionStatus(data.status);
            }
        })
        .fail(function() {
            console.warn('获取连接状态失败');
        });
}

function updateConnectionStatus(statusData) {
    Object.keys(statusData).forEach(configName => {
        const status = statusData[configName];
        const statusBadge = $(`#status-${configName}`);
        
        if (statusBadge.length === 0) return;
        
        if (status.success) {
            statusBadge.removeClass().addClass('badge bg-success').text('连接正常');
            if (status.response_time) {
                statusBadge.attr('title', `响应时间: ${status.response_time}ms`);
            }
        } else {
            statusBadge.removeClass().addClass('badge bg-danger').text('连接失败');
            if (status.error) {
                statusBadge.attr('title', `错误: ${status.error}`);
            }
        }
        
        // 更新检查时间
        if (status.check_time) {
            const checkTime = new Date(status.check_time);
            const now = new Date();
            const ageSeconds = Math.floor((now - checkTime) / 1000);
            
            if (ageSeconds < 60) {
                statusBadge.append(` <small>(${ageSeconds}秒前)</small>`);
            } else if (ageSeconds < 3600) {
                const minutes = Math.floor(ageSeconds / 60);
                statusBadge.append(` <small>(${minutes}分钟前)</small>`);
            }
        }
    });
}
</script>
{% endblock %}